var app = getApp();
const db = wx.cloud.database({
  env: 'cloud1-2g6vpgs796710242'
})
const _ = db.command

Page({
  data: {
    planet_info:[],
    translate:0,
    outtext2:"----------降重中，请稍等----------",
    lang:1,
    translate:0,
    ltype:"en",
    baiduToken:"",
    feedback:"",
    storage:[]
  },

  onLoad: function (options) {
    var user = wx.getStorage({
      key:'user',
      success: (res)=> {
        console.log("查询用户信息缓存",res.data)
        this.setData({
          storage:res.data
        })
      }
    })
    this.getbd_token()
    var id = options.id
    db.collection('cp_list')
    .doc(id)
    .get()
    .then(res=>{
      console.log(res)
      this.setData({
        planet_info:res.data
      })
      //更新CTR
      db.collection("cp_list")
      .doc(id)
      .update({
        data:{
          CTR:_.inc(1)
        }
      })
      .then(res=>{
        console.log("CTR自增成功",res)
      })
      if (!this.data.storage.name=="") {
        console.log('用户信息已授权',user)
        this.setData({
          hasUserInfo: true,
          userInfo: user,
        })
        console.log("用户信息", this.data.userInfo)
        console.log("全局openid",app.globalData.openid)

        db.collection("User")
        .where({
          _openid:app.globalData.openid
        })
        .get()
        .then(res=>{
          console.log("用户信息",res)
          var aimcp = this.data.planet_info.title
          for (var i = 0; i < res.data[0].common.length; i++) {
            if (res.data[0].common[i].name==aimcp) {
              db.collection("User")
              .where({
                _openid:app.globalData.openid,
                'common.name':aimcp
              })
              .update({
                data:{
                  "common.$.count":res.data[0].common[i].count+1
                }
              })
              .then(res=>{
                console.log("使用频次更新成功",res)
              })
              .catch(err=>{
                console.log(err)
              })
            }
          }
        })
      } else {
        console.log("无缓存用户信息")
      }
    })
    .catch(err=>{
      console.log("cp_list云数据库",err)
    })
  },

  transform_type() {
    //英文为0，中文为1
    if(this.data.lang==0) {
      this.setData({
        lang:1,
        ltype:"en"
      })
    } else {
      this.setData({
        lang:0,
        ltype:"zh"
      })
    }
    console.log("当前lang=",this.data.lang)
  },

  trigger() {
    console.log("ltype,输出的类型",this.data.ltype)
    if (this.data.feedback=="") {
      wx.showToast({ title: '请在输入框中填写需要降重的内容', icon: 'none' });
    } else {
      // API文档：https://ai.baidu.com/ai-doc/MT/4kqryjku9
      // 使用案例：https://blog.csdn.net/han_han__/article/details/127106843
      wx.request({
        url: 'https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token='+this.data.baiduToken,
        data: {
          "q":this.data.feedback,
          "from": "auto",
          "to": this.data.ltype,
        },
        header:{//请求头
          'Content-Type':	'application/json;charset=utf-8'
        },
        method:'POST',
        success: res => {
          console.log('success:', res)
          console.log('结果:',res.data.result.trans_result[0].dst)
          var outtext=res.data.result.trans_result[0].dst
          this.trigger_reverse(outtext)
        },
        fail: err => {
        console.log('fail:', err)
        }
      })
    }
  },

  trigger_reverse(e) {
    console.log("step2",e)
    this.setData({
      translate:1
    })
    //lang控制样式，ltype设置翻译配置
    if(this.data.ltype=="en") {
      this.setData({
        ltype:"zh"
      })
    } else {
      this.setData({
        ltype:"en"
      })
    }
    wx.request({
      url: 'https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token='+this.data.baiduToken,
      data: {
        "q": e,
        "from":'auto',
        "to": this.data.ltype,
      },
      header:{//请求头
        'Content-Type':	'application/json;charset=utf-8'
      },
      method:'POST',
      success: res => {
        console.log('success:', res)
        console.log('结果:',res.data.result.trans_result[0].dst)
        this.setData({
          outtext2: res.data.result.trans_result[0].dst
        })
        if(this.data.ltype=="en") {
          this.setData({
            ltype:"zh"
          })
        } else {
          this.setData({
            ltype:"en"
          })
        }
        console.log("结束后ltype的状态，选中中文时应该为en（输出类型）")
      },
      fail: err => {
       console.log('fail:', err)
      }
    })
  },

  literature(event) {
    var key = event.detail.value
    this.setData({
      feedback: key
    })
    console.log(this.data.feedback)
  },

  getbd_token() {
    var apiKey = 'AETTyYzdFm88y8i95iGRT003';    
    var secKey = 'DlwXkWhF4NHRtWRlGjG60xOtAqdp0IRu';  
    var tokenUrl = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+apiKey+"&client_secret="+secKey  
    var that = this;    
    wx.request({        
      url: tokenUrl,    
      payload:"",    
      method: 'POST',        
      dataType: 'json',        
      header:{            
        'Content-Type': 'application/json',
        'Accept': 'application/json'      
      },        
      success: function(res){            
        console.log("[BaiduToken获取成功]",res);            
        that.setData({                
          baiduToken: res.data.access_token
        })        
      },        
      fail: function(res){            
        console.log("[BaiduToken获取失败]",res);
      }    
    }) 
  },

})